<template>
  <div class="chat-container">
    <!-- 聊天窗口 -->
    <div class="chat-window" v-if="isConnected">
      <div class="chat-header">
        <h3>{{ chatTitle }}</h3>
        <el-button @click="endChat" type="danger" size="small">结束聊天</el-button>
      </div>
      
      <div class="messages-container" ref="messagesContainer">
        <div 
          v-for="message in messages" 
          :key="message.timestamp"
          :class="['message', message.fromUserId === currentUserId ? 'own-message' : 'other-message']"
        >
          <div class="message-content">
            <div class="message-sender">{{ message.fromUserId === currentUserId ? '我' : '对方' }}</div>
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
      </div>
      
      <div class="input-area">
        <el-input
          v-model="inputMessage"
          placeholder="输入消息..."
          @keyup.enter="sendMessage"
          :disabled="!isChatActive"
        >
          <template #append>
            <el-button @click="sendMessage" :disabled="!isChatActive">发送</el-button>
          </template>
        </el-input>
      </div>
    </div>
    
    <!-- 连接状态 -->
    <div v-else class="connection-status">
      <p>WebSocket未连接</p>
      <el-button @click="connectWebSocket" type="primary">连接聊天</el-button>
    </div>
    
    <!-- 在线用户列表（客服端可见） -->
    <div v-if="isCustomerService" class="online-users">
      <h4>在线用户</h4>
      <div 
        v-for="user in onlineUsers" 
        :key="user.userId"
        class="user-item"
        @click="startChatWithUser(user.userId)"
      >
        {{ user.userId }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// 组件属性
const props = defineProps({
  currentUserId: {
    type: String,
    required: true
  },
  isCustomerService: {
    type: Boolean,
    default: false
  }
})

// 响应式数据
const isConnected = ref(false)
const isChatActive = ref(false)
const chatTitle = ref('客服聊天')
const inputMessage = ref('')
const messages = ref([])
const onlineUsers = ref([])
const messagesContainer = ref(null)

// WebSocket实例
let websocket = null

// 连接WebSocket
const connectWebSocket = () => {
  try {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    const wsUrl = `${protocol}//${window.location.host}/websocket/chat`
    
    websocket = new WebSocket(wsUrl)
    
    websocket.onopen = () => {
      isConnected.value = true
      ElMessage.success('连接成功')
      
      // 发送用户身份信息
      const authMessage = {
        type: 'auth',
        userId: props.currentUserId
      }
      websocket.send(JSON.stringify(authMessage))
    }
    
    websocket.onmessage = (event) => {
      const message = JSON.parse(event.data)
      handleWebSocketMessage(message)
    }
    
    websocket.onclose = () => {
      isConnected.value = false
      isChatActive.value = false
      ElMessage.warning('连接已断开')
    }
    
    websocket.onerror = (error) => {
      console.error('WebSocket错误:', error)
      ElMessage.error('连接错误')
    }
    
  } catch (error) {
    console.error('连接WebSocket失败:', error)
    ElMessage.error('连接失败')
  }
}

// 处理WebSocket消息
const handleWebSocketMessage = (message) => {
  switch (message.type) {
    case 'system':
      ElMessage.info(message.content)
      if (message.content.includes('聊天已建立')) {
        isChatActive.value = true
        chatTitle.value = `与 ${message.fromUserId} 的聊天`
      }
      break
      
    case 'message':
      messages.value.push(message)
      scrollToBottom()
      break
      
    case 'error':
      ElMessage.error(message.content)
      break
      
    case 'online_users':
      onlineUsers.value = message.users
      break
  }
}

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim() || !isChatActive.value) return
  
  const message = {
    type: 'message',
    content: inputMessage.value.trim()
  }
  
  websocket.send(JSON.stringify(message))
  inputMessage.value = ''
}

// 开始与用户聊天（客服端功能）
const startChatWithUser = (targetUserId) => {
  const message = {
    type: 'start_chat',
    targetUserId: targetUserId
  }
  websocket.send(JSON.stringify(message))
}

// 结束聊天
const endChat = () => {
  const message = {
    type: 'end_chat'
  }
  websocket.send(JSON.stringify(message))
  isChatActive.value = false
  messages.value = []
  chatTitle.value = '客服聊天'
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 格式化时间
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString()
}

// 生命周期
onMounted(() => {
  connectWebSocket()
})

onUnmounted(() => {
  if (websocket) {
    websocket.close()
  }
})
</script>

<style scoped>
.chat-container {
  width: 100%;
  height: 500px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  display: flex;
}

.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f5f7fa;
}

.messages-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background-color: #fafafa;
}

.message {
  margin-bottom: 16px;
  display: flex;
}

.own-message {
  justify-content: flex-end;
}

.other-message {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 12px;
  border-radius: 8px;
  background-color: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.own-message .message-content {
  background-color: #409eff;
  color: white;
}

.message-sender {
  font-size: 12px;
  font-weight: bold;
  margin-bottom: 4px;
}

.message-text {
  margin-bottom: 4px;
}

.message-time {
  font-size: 10px;
  opacity: 0.7;
  text-align: right;
}

.input-area {
  padding: 16px;
  border-top: 1px solid #e4e7ed;
}

.connection-status {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
}

.online-users {
  width: 200px;
  border-left: 1px solid #e4e7ed;
  padding: 16px;
  background-color: #f5f7fa;
}

.user-item {
  padding: 8px 12px;
  margin-bottom: 8px;
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.user-item:hover {
  background-color: #e4e7ed;
}
</style>